using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System;
using System.IO;
using System.Xml;
using System.Diagnostics;
using System.Threading;
using System.Reflection;
using System.Security.Permissions;
using Microsoft.Office.Server.Search.Administration;
using Microsoft.Office.Server;
using Microsoft.Win32;
//using System.Runtime.InteropServices;

namespace Components2.PdfSearch {

    public class PdfSearchReceiver : SPFeatureReceiver {

        public override void FeatureInstalled(SPFeatureReceiverProperties properties) {

        }

        //[DllImport("KERNEL32.DLL")]
        //public static extern bool SetEnvironmentVariable(string VariableName, string VariableValue);

        public override void FeatureActivated(SPFeatureReceiverProperties properties) {
            SPFarm farm = properties.Definition.Farm;
            Process p;

            //todo: move the hardcoded paths to feature definition

            try {

                #region install ifilter
                Console.WriteLine("installing reader");
                try {
                    p = new Process();
                    p.StartInfo.FileName = @"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\adobereader.exe";
                    //qb-!
                    //todo: skip if already installe
                    p.StartInfo.Arguments = "/sAll /rs /l /msi\"/qn /norestart ALLUSERS=1 EULA_ACCEPT=YES AgreeToLicense=Yes SUPPRESS_APP_LAUNCH=YES\"";
                    p.StartInfo.UseShellExecute = false;
                    p.Start();
                    while (!p.HasExited) {
                        Console.Write(".");
                        Thread.Sleep(1000);
                    }
                } catch (Exception e) {
                    Console.WriteLine("error");
                    Console.WriteLine(e.ToString());
                }
                Console.WriteLine("done");
                #endregion

                #region set new registry keys and system paths
                Console.WriteLine("set registry keys");
                RegistryKey rkHKLM = Registry.LocalMachine;
                //Console.WriteLine("rkHKLM:" + rkHKLM);
                RegistryKey key = rkHKLM.OpenSubKey(@"SOFTWARE\Microsoft\Office Server\12.0\Search\Setup\ContentIndexCommon\Filters\Extension\.pdf", true);
                //Console.WriteLine("key1:" + key);
                //{4C904448-74A9-11D0-AF6E-00C04FD8DC02}
                key.SetValue(null, "{E8978DA6-047F-4E3D-9C78-CDBE46041603}");
                key.Flush();

                key = rkHKLM.OpenSubKey(@"SOFTWARE\Microsoft\Shared Tools\Web Server Extensions\12.0\Search\Setup\ContentIndexCommon\Filters\Extension\.pdf", true);
                //Console.WriteLine("key2:" + key);
                //{4C904448-74A9-11D0-AF6E-00C04FD8DC02}
                key.SetValue(null, "{E8978DA6-047F-4E3D-9C78-CDBE46041603}");
                key.Flush();

                string addpath = @"C:\Program Files\Adobe\Reader 9.0\Reader";
                key = rkHKLM.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true);
                //Console.WriteLine("key3:" + key);
                string path = key.GetValue("Path").ToString();
                if (!path.Contains(addpath)) {
                    path += ";" + addpath;
                }
                key.SetValue("Path", path);
                key.Flush();
                Console.WriteLine("done");
                #endregion

                #region restart search
                Console.WriteLine("restart search service");
                p = new Process();
                p.StartInfo.FileName = @"net";
                p.StartInfo.Arguments = "stop osearch";
                p.StartInfo.UseShellExecute = false;
                p.Start();
                while (!p.HasExited) {
                    Console.Write(".");
                    Thread.Sleep(1000);
                }
                p = new Process();
                p.StartInfo.FileName = @"net";
                p.StartInfo.Arguments = "start osearch";
                p.StartInfo.UseShellExecute = false;
                p.Start();
                while (!p.HasExited) {
                    Console.Write(".");
                    Thread.Sleep(1000);
                }
                Console.WriteLine("done");
                #endregion

                #region restart iis
                Console.WriteLine("restart iis");
                p = new Process();
                p.StartInfo.FileName = @"iisreset";
                p.StartInfo.Arguments = "/restart";
                p.StartInfo.UseShellExecute = false;
                p.Start();
                while (!p.HasExited) {
                    Console.Write(".");
                    Thread.Sleep(1000);
                }
                 Console.WriteLine("done");
                #endregion

                #region update docicon
                Console.WriteLine("update docicon");
                DirectoryInfo dirinfo = new DirectoryInfo(properties.Feature.Definition.RootDirectory);
                DirectoryInfo rootinfo = dirinfo.Parent.Parent.Parent;
                //Console.WriteLine("rootinfo: " + rootinfo);
                string filename = Path.Combine(rootinfo.FullName, @"TEMPLATE\XML\DOCICON.XML");
                XmlDocument xml = new XmlDocument();
                xml.Load(filename);
                //Console.WriteLine("xml loaded");
                XmlNode node = xml.SelectSingleNode("//Mapping[@Key='pdf']");
                if (node == null) {
                    Console.WriteLine("adding docicon");

                    string backup = filename + DateTime.Now.ToString("_yyyyMMddHHmmss") + ".bak";
                    File.Copy(filename, backup);
                    Console.WriteLine("backed up to: " + backup);

                    XmlNode nextsiblingnode = xml.SelectSingleNode("//Mapping[@Key='png']");
                    XmlNode newnode = xml.CreateElement("Mapping");
                    XmlAttribute attr = xml.CreateAttribute("Key");
                    attr.Value = "pdf";
                    newnode.Attributes.Append(attr);
                    attr = xml.CreateAttribute("Value");
                    attr.Value = @"c2\pdficon.gif";
                    newnode.Attributes.Append(attr);

                    nextsiblingnode.ParentNode.InsertBefore(newnode, nextsiblingnode);
                    xml.Save(filename); //todo: formatting if needed
                }
                Console.WriteLine("done");
                #endregion

                Console.WriteLine("finding spp");
                //Console.WriteLine(farm == null);
                SPWebService service = farm.Services.GetValue<SPWebService>("");
                //Console.WriteLine(service == null);
                foreach (SPWebApplication spWebApp in service.WebApplications) {
                    //Console.WriteLine(spWebApp.Name);
                    if (spWebApp.Properties.ContainsKey("Microsoft.Office.Server.SharedResourceProvider")) {
                        using (SPSite site = spWebApp.Sites[0]) {
                            using (SPWeb web = site.RootWeb) {
                                string template = null;
                                try {
                                    template = web.WebTemplate;
                                } catch (Exception e) {
                                    Console.WriteLine("No access to site collection");
                                    Console.WriteLine(site.Url);
                                    Console.WriteLine(e.ToString());
                                }
                                if (template == "OSRV") {
                                    Console.WriteLine("found:" + site.Url);
                                    ServerContext context = ServerContext.GetContext(site);
                                    SearchContext searchcontext = SearchContext.GetContext(context);
                                    Content sspContent = new Content(searchcontext);

                                    #region update ssp with pdf file type
                                    bool found = false;
                                    foreach (Extension ext in sspContent.ExtensionList) {
                                        if (ext.FileExtension.ToLower() == "pdf") {
                                            found = true;
                                        }
                                    }
                                    if (!found) {
                                        Console.WriteLine("adding ext");
                                        Extension ext = sspContent.ExtensionList.Create("pdf");
                                    }
                                    #endregion

                                    #region start full crawl
                                    foreach (ContentSource cs in sspContent.ContentSources) {
                                        if (cs.Name.Contains("auto")) {
                                            cs.StopCrawl();
                                            cs.StartFullCrawl();
                                        }
                                    }
                                    #endregion

                                }
                            }
                        }
                    }
                }
                Console.WriteLine("done");
                
            } catch (Exception e) {
                Console.WriteLine("error");
                Console.WriteLine(e.ToString());
            }
            Console.WriteLine("completed");
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties) {

        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties) {

        }
    }
}